/**
 * 测试pthread_cancel 函数 注意子线程如果没有用到系统调用的话，需要设置，检查点
 * 使用pthread_testcancel();  函数来设置；
 * @author: sundx
 * @date: 2020-05-27 15:04:28
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-27 16:05:03
 */
#include <iostream>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void *demo(void *argv);
int main() {
  pthread_t tid[5];
  int ret;

  for (int i = 0; i < 5; ++i) { // 循环创建；
    int ret = pthread_create(&tid[i], NULL, demo, (void *)i);
    if (ret != 0) {
      std::cout << "pthread_create failed " << strerror(ret) << std::endl;
    }
  }

  for (int i = 0; i < 5; ++i) { // 循环cancel；
    sleep(1);
    ret = pthread_cancel(tid[i]);
    if (ret != 0) {
      std::cout << "pthread_join failed " << strerror(ret) << std::endl;
    }
    std::cout << "main thread: " << pthread_self()
              << " the subPthread : " << tid[i] << std::endl;
  }

  pthread_exit(NULL);
  return 0;
}

void *demo(void *argv) {
  long m = (long)argv;
  sleep(m);
  std::cout << "tid: " << pthread_self() << std::endl;
  while (1) {
    usleep(100000);
    // pthread_testcancel();
    std::cout << m << std::endl;
  }

  return (void *)m;
}